<template>
	<hyb-page ref="page" :title="title">

		<template v-slot:top>

			<text class="sendmsg gui-block  gui-margin gui-primary-color" @tap="back()">返回</text>
		</template>
		<template v-slot:body>

			<!-- 抖音小程序直接显示抖音登录 -->
			<!-- #ifdef MP-TOUTIAO -->
			<view style="height: 90vh;"
				class="gui-bg-white gui-flex gui-column gui-align-items-center gui-justify-content-center">
				<gui-image :width="200" :height="200" class="gui-border-radius" :src="base.erweima" mode="aspectFit">
				</gui-image>

			<!-- 抖音登录按钮 -->
			<button 
				open-type="getUserInfo" 
				@getuserinfo="douyinDirectLogin" 
				@tap="login"
				:style="{
					backgroundColor: '#fe2c55',
					borderRadius: '40rpx',
					marginTop: '100rpx',
					padding: '20rpx 40rpx',
					border: 'none',
					color: 'white',
					fontSize: '32rpx'
				}">
				抖音一键登录
			</button>

			</view>
			<!-- #endif -->

			<!-- 其他平台显示原有登录界面 -->
			<!-- #ifndef MP-TOUTIAO -->
			<view v-if="base.denglu_fangshi==3" style="height: 90vh;"
				class="gui-bg-white gui-flex gui-column gui-align-items-center gui-justify-content-center">
				<gui-image :width="200" :height="200" class="gui-border-radius" :src="base.erweima" mode="aspectFit">
				</gui-image>

				<!-- 登录按钮 -->
				<view v-if="is_wechat == 4" @tap="weixin_login" style="background-color: #fe2c55;border-radius: 40rpx; margin-top:200rpx; padding: 20rpx 40rpx;">
					<text style="color: white; font-size: 32rpx;">抖音一键登录</text>
				</view>

			</view>

			<view v-else style="padding:50rpx;" class="gui-bg-white">
				<hyb-privacy ref="privacy" :content="base.xieyi" @change="privacyChange" v-model="checked"></hyb-privacy>
			</view>
			<!-- #endif -->
		</template>
	</hyb-page>
</template>

<script>
	export default {
		data() {
			return {
				title: "用户登录",
				checked: true,
			}
		},

		computed: {
			base: () => {
				return uni.storage.get("base");
			},
			userinfo: () => {
				return uni.storage.get("userinfo");
			},

			is_wechat: () => {
				// #ifdef MP-WEIXIN
				return 2; //微信小程序
				// #endif
				
				// #ifdef MP-TOUTIAO
				return 4; //抖音小程序
				// #endif

				// #ifdef H5
				if (uni.$jswx.isWechat()) {
					return 1; //微信浏览器
				} else {
					return 0;
				}
				// #endif

				// #ifdef APP
				return 3;
				// #endif
			},
		},

		onLoad(options) {
			// 抖音小程序直接显示抖音登录，不需要其他逻辑
		},

		methods: {
			login(){
				// 在抖音小程序平台中调用
				// #ifdef MP-TOUTIAO
				tt.getUserProfile({
				  success(res) {
				    console.log("getUserProfile 调用成功：", res.userInfo);
				    // 处理用户信息
				    const userInfo = res.userInfo;
				    // userInfo 包含：avatarUrl, nickName, gender, city, province, country, language
				  },
				  fail(res) {
				    console.log("getUserProfile 调用失败", res);
				    // 处理失败情况
				  }
				});
				// #endif
			},
			back() {
				let url = ""
				if (this.$store.state.base.hyzx_luj) {
					url = this.$store.state.base.hyzx_luj;
				} else {
					url = this.$store.base.menus[0].lianjie
				}
				uni.redirectTo({
					url: url,
					fail: () => {
						uni.reLaunch({
							url: "/hyb_o2o/index/index"
						})
					}
				})
			},


			// 抖音直接登录方法
			douyinDirectLogin(e) {
				let that = this;
				console.log('抖音登录事件:', e);
				
				// 检查是否获取到用户信息
				if (e.detail && e.detail.userInfo) {
					console.log('获取用户信息成功:', e.detail.userInfo);
					
					// 获取用户信息成功后，再获取登录code
					uni.login({
						provider: 'toutiao',
						success: function(loginRes) {
							console.log('抖音登录成功:', loginRes);
							let code = loginRes.code;
							
							uni.showLoading({
								title: '登录中...',
								mask: true
							});
							
							// 发送到后端
							uni.gPost("mp/login", {
								f_parentid: uni.storage.get("f_parentid"),
								code: code,
								platform: 'douyin',
								userInfo: e.detail.userInfo
							}).then((res) => {
								uni.hideLoading();
								console.log('抖音登录响应:', res);
								uni.storage.set("session_key", res.session_key || '');
								if (res.token) {
									// 登录成功，保存用户信息
									uni.storage.set("token", res.token);
									uni.storage.set("userinfo", res.userinfo);
									that.$store.commit("set_user", res.userinfo);
									
									uni.showToast({
										title: "抖音登录成功",
										icon: "success"
									});
									
									// 登录成功后返回或跳转
									setTimeout(() => {
										uni.navigateBack({
											delta: 2,
											fail: () => {
												that.back();
											}
										});
									}, 1000);
								} else {
									// 登录失败，显示错误信息
									uni.showToast({
										title: "登录失败，请重试",
										icon: "none"
									});
								}
							}).catch((error) => {
								uni.hideLoading();
								console.error('抖音登录错误:', error);
								uni.showToast({
									title: "登录失败，请重试",
									icon: "none"
								});
							});
						},
						fail: function(error) {
							console.error('抖音登录失败:', error);
							uni.showToast({
								title: "抖音登录失败",
								icon: "none"
							});
						}
					});
				} else {
					console.error('获取用户信息失败:', e);
					uni.showToast({
						title: "需要授权才能登录",
						icon: "none"
					});
				}
			},

			getWebUrl(name) {
				return name.split('#')[0]; //substring(0, name.indexOf('#'));
			},
			weixin_login() {
				let that = this;
				if (this.is_wechat == 1) {
					let href = this.getWebUrl(window.location.href) + "/login";
					let redirectUrl = encodeURIComponent(href);
					let appId = uni.storage.get("appId");
					window.location.href =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
				} else if (this.is_wechat == 2) {
					// 微信小程序登录
					uni.login({
						provider: 'weixin',
						success: function(res) {
							console.log(res);
							let code = res.code;
							uni.gPost("token", {
								f_parentid: uni.storage.get("f_parentid"),
								code: code
							}).then((res) => {
								uni.storage.set("session_key", res.session_key);
								if (res.token) {
									uni.storage.set("token", res.token);
									uni.storage.set("userinfo", res.userinfo);
									that.$store.commit("set_user", res.userinfo);

									uni.navigateBack({
										delta: 2,
										fail: () => {
											that.back();
										}
									})
								} else {
									uni.storage.set("openid", res.openid);
									uni.showToast({
										title: "用户未绑定，请使用手机号登录!",
										icon: "none"
									})
								}
							})
						}
					});
				} else if (this.is_wechat == 4) {
					// 抖音小程序登录 - 调用新的直接登录方法
					this.douyinDirectLogin();
				}
			},

			privacyChange(flag) {
				if (flag) uni.storage.set("xieyi", 1);
			},


		}
	}
</script>

<style>
	.login-logo {
		width: 180rpx;
		height: 180rpx;
		font-size: 80rpx;
		text-align: center;
		line-height: 120rpx;
		padding: 30rpx;
		border-radius: 18rpx;
	}

	.other-login-icons {
		width: 88rpx;
		height: 88rpx;
		text-align: center;
		font-size: 70rpx;
		margin: 20rpx;
	}
</style>
